<template>
  <div id="EmployeeManage">
    <Breadcrumb content="员工管理" />
    <div class="bodyContent">
      <Splitpanes style="height: 100%">
        <Pane :size="(650 / conWidth) * 100">
          <!-- 机构  -->
          <vxe-toolbar perfect ref="toolbarRef">
            <template #buttons>
              <div class="smallToolTitle">医院</div>
              <vxe-input style="width: 130px" v-model="orgForm.searchValue" type="search" clearable class="vxeInputSearch" placeholder="关键字查询" @clear="findOrgList" @keyup="keyupEnter" @search-click="handleSearch(orgForm.searchValue)"></vxe-input>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :loading="showLoading" @click="findOrgList"></vxe-button>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="新建" @click="addOrg('', '')"></vxe-button>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-save" content="保存" :loading="saveLoading" @click="saveOrg"></vxe-button>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-sort" content="同步数据" @click="pullOrg"></vxe-button>
            </template>
          </vxe-toolbar>
          <div class="tableBox">
            <vxe-table ref="orgTable" class="mytable-scrollbar" border="inner" height="auto" :data="orgaList" :loading="showLoading" :expand-config="{ expandAll: true, reserve: true }" @current-change="orgRowClick" :row-config="{ isCurrent: true, isHover: true }" :column-config="{ resizable: true }" :keyboard-config="{
                isArrow: true,
                isTab: true,
                isEdit: true
              }" :tree-config="{
                expandAll: true,
                transform: true,
                rowField: 'id',
                parentField: 'parentId'
              }" :edit-config="{ trigger: 'dblclick', mode: 'row', showStatus: true }" resizable show-overflow keep-source :reserve="true">
              <vxe-column field="code" title="编码" width="170" tree-node :edit-render="{}">
                <template #edit="{ row }">
                  <vxe-input type="text" :underline="false" v-model="row.code"></vxe-input>
                </template>
              </vxe-column>
              <vxe-column field="name" title="名称" min-width="110" :edit-render="{}">
                <template #edit="{ row }">
                  <vxe-input type="text" :underline="false" v-model="row.name"></vxe-input>
                </template>
              </vxe-column>
              <vxe-column title="操作" width="90" align="center" fixed="right">
                <template #default="{ row }">
                  <el-tooltip class="item" effect="dark" content="新建子分组" placement="left">
                    <vxe-button type="text" status="primary" icon="vxe-icon-square-plus" circle @click="addOrg(row.id, row)"></vxe-button>
                  </el-tooltip>
                  <vxe-button type="text" status="danger" icon="vxe-icon-delete" circle @click="deleteOrg(row)"></vxe-button>
                </template>
              </vxe-column>
            </vxe-table>
          </div>
        </Pane>
        <!-- 科室 -->
        <Pane :size="(650 / conWidth) * 100">
          <DeptsList ref="refDepts" @getCurrentOrgDept="getCurrentOrgDept" />
        </Pane>

        <Pane>
          <!-- 员工  -->
          <EmployeesList ref="refEmployees" />
        </Pane>
      </Splitpanes>
    </div>
  </div>
</template>

<script setup lang="ts">
// 引入组件区 ==========
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import Breadcrumb from '@/components/Breadcrumb.vue';
import { Splitpanes, Pane } from 'splitpanes';
let { proxy }: any = getCurrentInstance();
import { VXETable } from 'vxe-table';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage'; //提示框

import DeptsList from './DeptsList.vue'; //引用部门单独组件
import EmployeesList from './EmployeesList.vue'; //引用员工单独组件

import EditEmployees from '@/views/system_set/EditEmployees.vue'; //基本信息
import SetEmployPuthorization from '@/views/system_set/SetEmployPuthorization.vue'; //修改授权码
import EmpAuthDeparts from '@/views/system_set/EmpAuthDeparts.vue'; //授权部门
import Signature from '@/views/system_set/Signature.vue'; //电子签名
import EmpRelationUser from '@/views/system_set/EmpRelationUser.vue'; //员工添加关联用户
import { AppStore } from '../../stores/store';

// 全局变量定义区 ==========
let store = AppStore();
// 获取模块id
const moduleId = localStorage.getItem('moduleId');
// 功能点权限
let modulePoitPre = reactive([]);
// 通过权限获取功能点
let modulePointMap = store.userInfo.modulePointMap;

// 屏幕高度
let conHeight = ref(document.documentElement.clientHeight || document.body.clientHeight);

// 获取屏幕宽度
let conWidth = ref(document.documentElement.clientWidth);

let isChildren = ref(false); //是自己单独一个页面还是集合在其他页面下 true:作为子孩子集成在其他页面下，false:自己独立一个页面

let refDepts: any = ref(null); //点击机构把信息传递给部门子组件
let refEmployees: any = ref(null); //点击机构把信息传递给员工子组件

let showLoading = ref(false); //刷新加载状态
let saveLoading = ref(false); //保存加载状态

// 机构根据关键字查询
let orgForm = {
  id: '',
  parentId: null,
  parentName: '',
  name: '',
  code: '',
  tenantId: null,
  //用户输入查询内容
  searchValue: ''
};

let orgTable = ref(); //机构表格ref
let orgaList: any = reactive([]); //机构列表数据

// 方法定义区 =============
// 页面加载时更新组织机构列表(左侧)
onMounted(() => {
  findOrgList();
});

// 点击机构当前行触发的事件
function orgRowClick({ row }: any) {  
  (proxy.$refs.orgTable as any).setCurrentRow(row);
  refDepts.value.initPage(row); //给部门传值
  const params = {
    orgId: row.id
  };
  refEmployees.value.initPage(params); //给员工传值
}

// 父组件接收子组件部门传回来的机构部门信息
function getCurrentOrgDept(row: any) {  
  const params = {
    deptId: row.id,
    orgId: row.orgId
  };
  refEmployees.value.initPage(params);
}

// 获取机构列表(默认获得全部)
function findOrgList() {
  showLoading.value = true;
  const $table = proxy.$refs.orgTable;
  if ($table) {
    $table.setAllRowExpand(true);
    $table.setAllTreeExpand(true);
  }
  const url = '/api/sys/findOrganizationPageList';
  orgaList.length = 0; //放入数据前清空数据
  proxy.$http
    //注意此处的数据条数
    .get(url, { params: { pageIndex: 1, pageSize: 50 } })
    .then((res: any) => {
      orgaList.push(...res.data.records);
      orgRowClick({ row: orgaList[0] }); //默认选中第一条数据
      $table.setAllTreeExpand(true);
      // $table.loadData(orgaList,true);
      showLoading.value = false;
    })
    .catch((err: any) => {
      showLoading.value = false;
      // VxeMessage('获取机构列表失败',VxeNotifyType.error)
    });
}

// 查询/刷新
function handleSearch(row: string | number) {
  const $table = orgTable.value;
  if ($table) {
    $table.setAllRowExpand(true);
    $table.setAllTreeExpand(true);
  }
  const url = '/api/sys/findOrganizationPageList';
  orgaList.length = 0;
  proxy.$http
    .get(url, { params: { keywords: row, pageIndex: 1, pageSize: 50 } })
    .then((res: any) => {
      orgaList.push(...res.data.records);
      orgRowClick({ row: orgaList[0] }); //默认选中第一条数据
      $table.setAllRowExpand(true);
      $table.setAllTreeExpand(true);
      // $table.loadData(orgaList, true);
    })
    .catch((err: any) => {
      // VxeMessage('查询刷新失败', VxeNotifyType.error);
    });
}
// 回车查询
function keyupEnter(e: any) {
  if (e.$event.code == 'Enter') {
    handleSearch(orgForm.searchValue);
  }
}
// 清空搜索条件
function clearForm() {
  orgForm = {
    id: '',
    parentId: null,
    parentName: '',
    name: '',
    code: '',
    tenantId: null,
    //用户输入查询内容
    searchValue: ''
  };
}

// 同步数据
function pullOrg() {
}

//**判断为空*/
function IsEmpty(value: any) {
  if (value === undefined || value === '' || value === null) {
    return true;
  }
  if (JSON.stringify(value) === '{}') {
    return true;
  }
  return false;
}

// 新建一级机构/子结构
async function addOrg(parentids: any, row: any): Promise<void> {
  //clearForm();
  const $table = orgTable.value;
  if ($table) {
    // 获取新增的数据记录
    const record = {
      code: '',
      name: '',
      parentId: parentids != '' || parentids != null ? parentids : null,
      id: ''
    };
    // orgaList.push(record);
    // $table.loadData(orgaList);
    const { row: newRow } = await $table.insertAt(record, -1);
    await $table.setEditRow(record);
    if (row) {
      await $table.setTreeExpand(row, true); // 新建一行空数据时展开这一栏
    }
  }
}

// 保存
async function saveOrg() {
  saveLoading.value = true;
  const $table = proxy.$refs.orgTable;
  if ($table) {
    const updateRecords = await $table.getUpdateRecords().filter((p: any) => {
      return p.id !== '';
    });

    const InsertRecords = await $table.getInsertRecords().filter((m: any) => {
      return m.id === '';
    });

    $table.setAllRowExpand(true);
    $table.setAllTreeExpand(true);

    // 修改机构
    updateRecords.forEach((e: any) => {
      const url = '/api/sys/editOrg';
      const tOrganization = e;
      proxy.$http
        .post(url, tOrganization)
        .then((res: any) => {
          $table.setAllTreeExpand(true);
          VxeMessage('修改机构成功', VxeNotifyType.success);
        })
        .catch((err: any) => {
          VxeMessage('修改机构失败', VxeNotifyType.error);
        });
    });

    // 新增机构
    InsertRecords.forEach((ele: any) => {
      const url = '/api/sys/addOrg';
      const tOrganization = ele;
      proxy.$http
        .post(url, tOrganization)
        .then((res: any) => {
          $table.setAllTreeExpand(true);
          VxeMessage('新增机构成功', VxeNotifyType.success);
        })
        .catch((err: any) => {
          VxeMessage('新增机构失败', VxeNotifyType.error);
        });
    });
    setTimeout(() => {
      saveLoading.value = false;
    }, 500);
    findOrgList();
  }
}

// 删除机构
function deleteOrg(row: any) {
  const $table = orgTable.value;
  $table.setAllTreeExpand(true);
  $table.setAllRowExpand(true);
  proxy
    .$confirm('确定删除此组织机构？', '提示', {
      cancelButtonClass: 'cancel-button',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(async () => {
      const url = '/api/sys/deleteOrgOrDept/' + row.id;
      if (row.id) {
        proxy.$http.delete(url).then((res: any) => {
          if (res.status.code === 400) {
            VxeMessage('该机构下存在机构信息，不能删除', VxeNotifyType.error);
          } else {
            VxeMessage('删除机构成功', VxeNotifyType.success);
          }
          findOrgList();
          $table.setAllTreeExpand(true);
        });
      } else {
        if ($table) {
          await $table.remove(row);
          VxeMessage('删除机构成功', VxeNotifyType.success);
        }
      }
    })
    .catch((err: any) => {
      VxeMessage(err, VxeNotifyType.error);
    });
}
</script>

<style lang="scss" scoped>
#EmployeeManage {
  width: 100%;
  height: 100%;

  .bodyContent {
    height: calc(100% - 60px);
    // 附加按钮间距
    .button-blue {
      margin: 5px 0 5px 5px;
    }

    // 机构表格
    :deep(.vxe-table--render-default) {
      height: 100%;
    }
    :deep(.vxe-table--render-wrapper) {
      height: 100%;
      background-color: $base-white;
    }
    .tableBox {
      height: calc(100% - 39px);
    }
  }
}
</style>
